package com.yudaxian.bi.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: yudaxian
 * @Description: Excel工具类
 * @DateTime: 2024/9/18 15:03
 **/
@Slf4j
public class ExcelUtils {

    public static String excelToCsv(MultipartFile multipartFile) {

        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.info("读取Excel文件失败", e);
        }
        // 转换为csv
        // 读取表头
        if (CollectionUtil.isEmpty(list)) {
            return "";
        }

        LinkedHashMap<Integer, String> headMap = (LinkedHashMap) list.get(0);
        List<String> headList = headMap.values().stream().filter(s -> !StringTools.isEmpty(s)).collect(Collectors.toUnmodifiableList());

        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.join(headList, ",")).append("\n");

        // 读取每一行数据
        for (int i = 1; i < list.size(); i++) {
            Map<Integer, String> dataMap = (LinkedHashMap) list.get(i);
            List<String> dataList = dataMap.values().stream().filter(s -> !StringTools.isEmpty(s)).collect(Collectors.toUnmodifiableList());
            sb.append(StringUtils.join(dataList, ",")).append("\n");
        }
        return sb.toString();
    }

}
